package com.deep.bilibili.ffmpeg;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

public class LiveStream extends Thread {
    String line = "";

    private Process process;
    List<String> command = null;

    public LiveStream(List<String> command) {
        this.command = command;
    }

    public void run() {
        try {
            System.out.println("start push live ...... ");
//            Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();
//            new PrintStream(videoProcess.getErrorStream()).start();
            // 运行cmd命令，获取其进程
            process = Runtime.getRuntime().exec(command.toString());
            // 输出ffmpeg推流日志
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));


            new Thread(new Runnable() {
                @Override
                public void run() {
                    //这个控制台没被注销则检查。
                    while(true) {
                        String string = line;
                        try {
                            Thread.sleep(7000);
                        } catch (InterruptedException e) {
                        }
                        // 10s一判断
                        if(line.equals(string)){
                            process.destroy();
//                            if(!LiveApplication.urls.contains(params)) {
//                                System.out.println("已退出登录！转流结束！");
//                                break;
//                            }
                            System.err.println("转流失败，重新尝试转流！");
                            new LiveStream(command).start();
                            break;
                        }
                    }
                }
            }).start();
            while ((line = br.readLine()) != null) {
                System.out.println("视频推流信息[" + line + "]");
            }
            if (process != null) process.destroy();
            System.err.println("<<<<<<<<<<<<<<<<<<<<销毁 转流进程！");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}